package com.david.utils;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import cn.dev33.satoken.exception.NotRoleException;
import com.david.vo.CardBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * @author David
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 对Controller层输入的数据进行校验,validation
     * @param e 异常对象
     * @return 返回状态码及其message
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseBody
    public CardBean byExceptionHandler(MethodArgumentNotValidException e){
        CardBean baseBean = new CardBean();
        baseBean.setCode(1);

        // 用子类来类型转换取得字数少的message
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        //多个错误，取第一个
        FieldError error = fieldErrors.get(0);

        baseBean.setMsg(error.getDefaultMessage());
        return baseBean;
    }

    @ExceptionHandler(value = NullPointerException.class)
    public void catException(Exception e){
        log.error("空指针异常，原因为：" + e.toString());
    }

    @ExceptionHandler(value = IllegalArgumentException.class)
    @ResponseBody
    public CardBean catIllegal(IllegalArgumentException e){
        CardBean baseBean = new CardBean();
        baseBean.setMsg("不合法的参数");
        baseBean.setCode(1);
        log.warn("参数不合法的请求：" + e.getMessage());
        return baseBean;
    }

    /**
     * 拦截sa-token给的异常
     * @param e 异常
     * @return 返回异常
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public CardBean handlerNotLoginException(Exception e){
        String message = e.getMessage();
        int code;
        // 判断场景值，定制化异常信息
        if (e instanceof NotLoginException) {
            log.info("登录状态异常，原因为：" + message);
            code = 401;
        } else if(e instanceof NotRoleException) {
            log.info("该账户没有相应的管理员角色:" + message);
            code = 402;
        } else if(e instanceof NotPermissionException) {
            log.info("该账户没有相应的权限:" + message);
            code = 403;
        } else {	// 普通异常, 输出：500 + 异常信息
            code = 500;
        }

        // 返回给前端
        CardBean cardBean = new CardBean();
        cardBean.setMsg("别白费力气了，你没有这个权限");
        cardBean.setCode(code);
        return cardBean;
    }

}
